package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshBase;
import com.alibaba.mobileim.fundamental.widget.refreshlist.PullToRefreshListView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.QuestAnswerAdapter;
import com.wbao.dianniu.adapter.UserInfoHolder;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.MyListView;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.customView.PictureAndTextEditorView;
import com.wbao.dianniu.customView.SpanTextView;
import com.wbao.dianniu.data.Childrens;
import com.wbao.dianniu.data.KnowImageData;
import com.wbao.dianniu.data.KnowledgeData;
import com.wbao.dianniu.data.QuestAnswerListData;
import com.wbao.dianniu.emojiUtils.DisplayUtils;
import com.wbao.dianniu.emojiUtils.EmotionMainFragment;
import com.wbao.dianniu.http.ErrorCode;
import com.wbao.dianniu.listener.IKnowAnswerAddListener;
import com.wbao.dianniu.listener.IKnowAnswerDelListener;
import com.wbao.dianniu.listener.IKnowAnswerListListener;
import com.wbao.dianniu.listener.IKnowGoodListener;
import com.wbao.dianniu.listener.IKnowledgeCollectListener;
import com.wbao.dianniu.listener.IKnowledgeDelListener;
import com.wbao.dianniu.listener.IKnowledgeDetailListener;
import com.wbao.dianniu.listener.IScoreReduceListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.manager.KnowAnswerAddManger;
import com.wbao.dianniu.manager.KnowAnswerDelManger;
import com.wbao.dianniu.manager.KnowAnswerListManger;
import com.wbao.dianniu.manager.KnowDelManager;
import com.wbao.dianniu.manager.KnowDetailManager;
import com.wbao.dianniu.manager.KnowGoodManager;
import com.wbao.dianniu.manager.KnowledgeCollectManager;
import com.wbao.dianniu.update.KnowledgeHelper;
import com.wbao.dianniu.manager.ScoreReduceManager;
import com.wbao.dianniu.update.ScoreChangeManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.update.ErrorDialogHelper;
import com.wbao.dianniu.update.TwoComDataChangeManager;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.AnswerListType;
import com.wbao.dianniu.utils.CommentLongClickHelper;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.data.KnowPraseData;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.ReportType;
import com.wbao.dianniu.utils.SerializableMap;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 知识分享详情
 * <p>
 * Created by Administrator on 2017/9/11.
 */

public class KnowDetailActivity extends AppCompatActivity implements View.OnClickListener, IKnowledgeDetailListener, IKnowGoodListener, IKnowledgeDelListener,
        KnowledgeHelper.IKnowledgeChangedListener, IScoreReduceListener, IKnowAnswerListListener, IKnowAnswerAddListener, CommentLongClickHelper.ICommentLongListener
        , IKnowAnswerDelListener, TwoComDataChangeManager.ITwoComDataChangerListener, IKnowledgeCollectListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;

    private PullToRefreshListView pullListView;
    private ListView myListView;

    private ImageButton backImageBtn;
    private TextView titleTV;

    // addHeadView
    private int knowledgeId;
    private TextView mTitleTV;
    private TextView answerTV;
    private TextView praiseTV;
    private TextView forwardTV;
    private TextView deleteTV;
    private LinearLayout conentLayout;
    private SpanTextView mSpanTextView;
    private TextView scoreCountTV;
    private Button readKnowBtn;
    private LinearLayout commentLayout;
    private View allComment;
    private TextView commentCountsTV;

    //    private TextView visitorTV;
    private final String imageStart = "<img src=\"";

    private final String imageEnd = "\">";
    private KnowledgeData knowledgeData;

    //    private HtmlTextView htmlTextView;
    // 干货详情Manager
    private KnowDetailManager manager;
    // 干货点赞Manager
    private KnowGoodManager goodManger;
    // 干货删除Manager
    private KnowDelManager delManager;
    // 积分扣除Manager
    private ScoreReduceManager scoreReduceManager;
    // 干货回答列表Manger
    private KnowAnswerListManger answerListManager;
    // 干货回答Manager
    private KnowAnswerAddManger answerAddManger;
    // 干货回答删除
    private KnowAnswerDelManger answerDelManger;
    private Dialog dialog;

    private KnowledgeHelper knowledgeHelper;
    private QuestAnswerAdapter adapter;
    private final int PAGE_COUNTS = 10;
    private int currentPage = 0;
    private UserInfoHolder holder;
    //    private CommentLongClickHelper commentLongClickHelper;
    private InputMethodManager mInputManager;//软键盘管理类
    private EmotionMainFragment emotionMainFragment;
    private EditText bar_edit_text;
    private ImageView bar_image_add_btn;
    private Button bar_btn_send;
    private ImageView chosePicIV;
    private ImageView aFriendIV;
    private CheckBox checkBox;

    private Map<Integer, String> replyMap = new HashMap<>();
    private boolean IsPullDown = false;
    private int REQ_CODE = 120;
    private TwoComDataChangeManager twoComDataChangeManager;
//    private LinearLayout emojiBarLayout;
    /**
     * 标题右边图片
     */
    private ImageButton rightImageBtn;
    private KnowledgeCollectManager knowledgeCollectManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityUtils.setStatusBarColor(this);

        setContentView(R.layout.activity_know_detail);
        getData();
        initWattingView();
        initView();
        addHeadView();
        initEmotionMainFragment();
        initData();
        initListener();
//        initListView();
    }

    private void initListener() {
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                QuestAnswerListData data = (QuestAnswerListData) adapter.getItem(position - 3);
                // 进入二级回复界面
                ActivityUtils.intoTwoCommentActivity(KnowDetailActivity.this, data.knowledgeId, data.id, AnswerListType.TYPE_KNOW, data);
            }
        });


    }

    private void initWattingView() {
        waittingLayout = findViewById(R.id.waitting_layout);
        waittingProBar = findViewById(R.id.waitting_progress);
        waittingTV = findViewById(R.id.waitting_text_desc);
    }

    private void getData() {
        Intent intent = getIntent();
        String id = intent.getStringExtra(Const.INTENT_SCHEME_ID);
        if (null != id) {
            knowledgeId = Integer.valueOf(id);
        } else {
            knowledgeId = intent.getIntExtra(Const.INTENT_ID, 0);
        }
        knowledgeData = new KnowledgeData();
        knowledgeData.setId(knowledgeId);
    }

    private void addHeadView() {
        holder = new UserInfoHolder();
        View headView = LayoutInflater.from(this).inflate(R.layout.know_headview, null);
        holder.headIV = headView.findViewById(R.id.user_head);
        holder.nameTV = headView.findViewById(R.id.user_name);
        holder.labelTV = headView.findViewById(R.id.user_label);
        holder.sexIV = headView.findViewById(R.id.user_sex);
        holder.partnerIV = headView.findViewById(R.id.user_partner);
        holder.addV = headView.findViewById(R.id.add_v_iv);
        holder.headInfoLayout = headView.findViewById(R.id.user_head_layout);


        deleteTV = headView.findViewById(R.id.include_delete_tv);
        forwardTV = headView.findViewById(R.id.include_forward_tv);
        praiseTV = headView.findViewById(R.id.include_praise_tv);
        answerTV = headView.findViewById(R.id.include_answer_tv);

        mTitleTV = headView.findViewById(R.id.know_detail_title);
        conentLayout = headView.findViewById(R.id.know_detail_contentLayout);

        scoreCountTV = headView.findViewById(R.id.score_count);
        readKnowBtn = headView.findViewById(R.id.read_knowledge_btn);

        praiseTV.setOnClickListener(this);
        forwardTV.setOnClickListener(this);
        holder.headInfoLayout.setOnClickListener(this);
        holder.headIV.setOnClickListener(this);
        readKnowBtn.setOnClickListener(this);

        myListView.addHeaderView(headView);
        allComment = LayoutInflater.from(this).inflate(R.layout.all_comment_layout, null);
        commentCountsTV = allComment.findViewById(R.id.all_comment_counts_tv);
        myListView.addHeaderView(allComment);
        adapter = new QuestAnswerAdapter(this, AnswerListType.TYPE_KNOW);
        myListView.setAdapter(adapter);
        headView.setOnClickListener(null);
        allComment.setOnClickListener(null);

    }

    private void initView() {
        // title
        backImageBtn = findViewById(R.id.back_button);
        titleTV = findViewById(R.id.title);
        rightImageBtn = (ImageButton) findViewById(R.id.right_imagebutton);
        titleTV.setText("查看干货");
        backImageBtn.setOnClickListener(this);
        rightImageBtn.setVisibility(View.VISIBLE);
        rightImageBtn.setImageResource(R.drawable.sandian);
        rightImageBtn.setOnClickListener(this);

        // content
        pullListView = findViewById(R.id.know_detail_refresh_view);
        pullListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullListView.setOnRefreshListener(onRefreshListener);
        myListView = pullListView.getRefreshableView();
        myListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
        registerForContextMenu(myListView);

        // emoji Fragment
        initEmojiView();

    }

    private void initEmojiView() {
//        emojiBarLayout = (LinearLayout) findViewById(R.id.include_emoji_bar_layout);
        commentLayout = findViewById(R.id.know_detail_comment_layout);
        checkBox = findViewById(R.id.am_release_checkbox);
        checkBox.setButtonDrawable(R.drawable.xq_checkbox_unpress);
        checkBox.setClickable(false);
        bar_image_add_btn = findViewById(R.id.bar_image_add_btn);
        bar_btn_send = findViewById(R.id.bar_btn_send);
        bar_btn_send.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                // 未完善资料，不能回复评论
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(KnowDetailActivity.this);
                    return;
                }
                String comment = bar_edit_text.getText().toString().trim();
                if (null == comment || "".equals(comment)) {
                    Notification.toast(KnowDetailActivity.this, "请输入你的评论!");
                    return;
                }
                addAnswerComment(comment);
                // 隐藏键盘
                emotionMainFragment.onBackPress();
            }
        });
        bar_edit_text = findViewById(R.id.bar_edit_text);
        bar_edit_text.setOnClickListener(this);
        bar_edit_text.setOnEditorActionListener(actionListener);
        bar_edit_text.addTextChangedListener(watcher);
        chosePicIV = findViewById(R.id.bar_image_chose_pic);
        aFriendIV = findViewById(R.id.bar_image_a_friends);
        chosePicIV.setOnClickListener(this);
        aFriendIV.setOnClickListener(this);
//        if (!GlobalContext.getPerfectData()) {
//            emojiBarLayout.setVisibility(View.GONE);
//            bar_edit_text.setFocusable(false);
//            bar_btn_send.setFocusable(false);
//        } else {
//        }
    }

    private void initEmotionMainFragment() {
        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //构建传递参数
        Bundle bundle = new Bundle();
        //绑定主内容编辑框
        bundle.putBoolean(EmotionMainFragment.BIND_TO_EDITTEXT, true);
        //隐藏控件
        bundle.putBoolean(EmotionMainFragment.HIDE_BAR_EDITTEXT_AND_BTN, false);
        //替换fragment
        //创建修改实例
        emotionMainFragment = EmotionMainFragment.newInstance(EmotionMainFragment.class, bundle);
        emotionMainFragment.bindToContentView(pullListView, bar_image_add_btn, bar_edit_text);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in thefragment_container view with this fragment,
        // and add the transaction to the backstack
        transaction.replace(R.id.fl_emotionview_main, emotionMainFragment);
        transaction.addToBackStack(null);
        //提交修改
        transaction.commit();

    }


    private void initData() {
        manager = new KnowDetailManager(this);
        manager.addKnowledgeDetailListener(this);
        goodManger = new KnowGoodManager(this);
        goodManger.addKnowGoodListener(this);
        delManager = new KnowDelManager(this);
        delManager.addKnowledgeDelListener(this);
        scoreReduceManager = new ScoreReduceManager(this);
        scoreReduceManager.addScoreReduceListener(this);
        answerListManager = new KnowAnswerListManger(this);
        answerListManager.addknowAnswerListListener(this);
        answerAddManger = KnowAnswerAddManger.getInstance(this);
        answerAddManger.addknowAnswerAddListener(this);
        knowledgeHelper = KnowledgeHelper.getInstance();
        knowledgeHelper.addListener(this);
        answerDelManger = new KnowAnswerDelManger(this);
        answerDelManger.addknowAnswerDelListener(this);
        knowledgeCollectManager = new KnowledgeCollectManager(this);
        knowledgeCollectManager.addknowCollectListener(this);

        CommentLongClickHelper.getInstance().addCommentLongClickListener(this);
        twoComDataChangeManager = TwoComDataChangeManager.getInstance();
        twoComDataChangeManager.addCommentChangeListener(this);

        // 先请求详情数据 再请求回答列表
        reqData();

    }


    private void reqData() {
        manager.knowledgeDetail(GlobalContext.getAccountId(), knowledgeId);
    }

    private void reqAnswerList(int page) {
        answerListManager.knowAnswerList(GlobalContext.getAccountId(), knowledgeId, page * PAGE_COUNTS, PAGE_COUNTS, 0);
    }


    PullToRefreshBase.OnRefreshListener2 onRefreshListener = new PullToRefreshBase.OnRefreshListener2() {
        @Override
        public void onPullDownToRefresh() {
            pullDownRequest();
        }

        @Override
        public void onPullUpToRefresh() {
            pullUpRequest();
        }
    };

    // 上拉刷新数据请求
    private void pullUpRequest() {
        IsPullDown = false;
        //没有搜索结果 或者数据为空 上拉没有效果
        currentPage++;
        reqAnswerList(currentPage);

    }

    private void pullDownRequest() {
        IsPullDown = true;
        currentPage = 0;
        reqAnswerList(currentPage);
    }


    @Override
    public void onKnowledgeDetailFailure(int errorCode, String errorMsg) {
        if (errorCode == ErrorCode.KNOWLEDGE_ALEARY_DEL) {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText(errorMsg == null ? "" : errorMsg);
            knowledgeHelper.deleteNotify(knowledgeId);
        } else {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText(errorMsg == null ? "" : errorMsg);
        }
    }

    @Override
    public void onKnowledgeDetailSuccess(KnowledgeData data) {
//
        knowledgeData = data;
        if (null != data) {
            // 显示前 先清空content的内容
            conentLayout.removeAllViews();
            display(knowledgeData);
            // 审核中的干货和审核失败的干货不允许评论，隐藏评论按钮--也不加载评论详情
            if (KnowledgeData.STATUS_PASS == data.getStatus()) {
                // 请求完详情数据再请求回答列表
                reqAnswerList(currentPage);
                // 更新列表回复数
                knowledgeHelper.replyNotify(data.getId(), data.getAnswerCount());
                knowledgeHelper.goodNotify(data.getId(), data.getIsGood(), data.getGoodCount());
            } else {
                waittingLayout.setVisibility(View.GONE);
                myListView.removeHeaderView(allComment);
                commentLayout.setVisibility(View.GONE);
            }

        }

    }

    private void display(KnowledgeData data) {
        mTitleTV.setText(data.getSubject() == null ? "" : data.getSubject());
        PictureDownloadUtils.displayHeadImage(this, holder.headIV, data.getUserInfo().headPic);
        holder.nameTV.setText(data.getUserInfo().realName);
        holder.labelTV.setText(data.getUserInfo().label);
        Utils.showSex(this, data.getUserInfo().sex, holder.sexIV);
        Utils.showPartner(this, data.getUserInfo().partner, holder.partnerIV);
        Utils.showAuth(data.getUserInfo(), holder.addV);
        Utils.showPriseCounts(data.getAnswerCount(), answerTV);
        showCounts(data.getAnswerCount());
        Utils.praiseChanged(this, data.getIsGood(), data.getGoodCount(), praiseTV);
        if (GlobalContext.getAccountId() == data.getUserInfo().accountId) {
            deleteTV.setVisibility(View.VISIBLE);
            deleteTV.setOnClickListener(this);
        } else {
            deleteTV.setVisibility(View.GONE);
        }

        if (data.getStatus() == KnowledgeData.STATUS_INIT || data.getStatus() == KnowledgeData.STATUS_REFUSE) {
            // 屏蔽 回复，分享，删除按钮
            answerTV.setVisibility(View.INVISIBLE);
            praiseTV.setVisibility(View.INVISIBLE);
            forwardTV.setVisibility(View.INVISIBLE);
        }

        GlobalUserData userData = new GlobalUserData();
        userData.setScore(data.getLookAccountScore());
        ScoreChangeManager scoreChangeManager = ScoreChangeManager.getInstance();
        scoreChangeManager.updateScore();
        String my_score = String.format(getResources().getString(R.string.my_score_detail), data.getLookAccountScore() + "");
        scoreCountTV.setText(my_score);
        // 是否已经支付积分:0未支付，1已经支付
        if (0 == data.getIsScoreBuy() && data.getScore() > 0) {
            readKnowBtn.setVisibility(View.VISIBLE);
            scoreCountTV.setVisibility(View.VISIBLE);
            if (null != data.getUserInfo()) {
            }
            String reduce_score = String.format(getResources().getString(R.string.reduce_score), data.getScore() + "");
            readKnowBtn.setText(reduce_score);
        } else if (1 == data.getIsScoreBuy() || 0 == data.getScore()) {
            readKnowBtn.setVisibility(View.GONE);
            scoreCountTV.setVisibility(View.GONE);
        }

        String content = data.getContent();
        /**
         * 步骤：
         * 1。先把内容分隔成不同的List<KnowPraseData> 列表形式
         * 2。根据不同的内容，生成多个SpanTextView布局，分别封装该内容
         * 3。对于纯文本内容，做@处理
         * 4。回归调用完成，显示内容，并对内容做点击事件处理
         */
        List<KnowPraseData> praseList = splitImageContentByImages(content, data.getNoticeJson());
        insertContent(praseList, 0);

    }


    private String getHtmlString(String content) {
        Pattern p = Pattern.compile("\\{\"image\":[^}]*\\}");
        Matcher m = p.matcher(content);
        List<KnowImageData> resultList = new ArrayList<KnowImageData>();
        while (m.find()) {
            String tmp = m.group();
            KnowImageData imageData = JsonUtil.toObject(tmp, KnowImageData.class);
            imageData.content = tmp;
            imageData.type = 2;
            resultList.add(imageData);
        }
        for (int i = 0; i < resultList.size(); i++) {
            content = content.replace(resultList.get(i).content, imageStart + GlobalContext.cdndownUrl + resultList.get(i).image + imageEnd);
        }
        return content;
    }

    private void showCounts(int counts) {
        String str = String.format(getResources().getString(R.string.all_comment_counts), counts + "");
        commentCountsTV.setText(str);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_head:
            case R.id.user_head_layout:
                ActivityUtils.intoHeadInfoActivity(knowledgeData.getUserInfo().accountId, KnowDetailActivity.this);
                break;
            case R.id.include_praise_tv:
                int goodCounts = knowledgeData.getGoodCount();
                if (0 == knowledgeData.getIsGood()) {
                    knowledgeData.setIsGood(1);
                    goodCounts++;
                } else {
                    knowledgeData.setIsGood(0);
                    goodCounts--;
                }
                knowledgeData.setGoodCount(goodCounts);
//                Utils.praiseChanged(this, knowledgeData.getIsGood(), knowledgeData.getGoodCount(), praiseTV);
                // 请求点赞接口
                goodManger.knowGood(GlobalContext.getAccountId(), knowledgeData.getId());
                // 通知界面改变点赞状态
                knowledgeHelper.goodNotify(knowledgeId, knowledgeData.getIsGood(), knowledgeData.getGoodCount());
                break;
            case R.id.include_forward_tv:
                String imageUrl = imageUrl = GlobalContext.cdndownUrl + "logo.png";
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(KnowDetailActivity.this, knowledgeData.getShortContent(), 8, imageUrl, knowledgeData.getId());
                break;
            case R.id.include_delete_tv:
                showDeleteDialog();
                break;
            case R.id.read_knowledge_btn:
                // 正在扣除积分等待框
                scoreReduceManager.scoreReduce(GlobalContext.getAccountId(), 6, knowledgeId);
                break;
            case R.id.back_button:
                finish();
                break;
            case R.id.bar_image_a_friends:
                Intent aIntent = new Intent();
                aIntent.setClass(KnowDetailActivity.this, SelectFriendActivity.class);
                startActivityForResult(aIntent, REQ_CODE);
                break;
            case R.id.bar_image_chose_pic:  // 一级回复选择图片
                SerializableMap map = new SerializableMap();
                map.setMap(replyMap);
                Bundle bundle = new Bundle();
                bundle.putInt(WithPicCommentActivity.COMMENT_QUESTID, knowledgeId);
                bundle.putString(WithPicCommentActivity.Comment_Content, bar_edit_text.getText().toString());
                bundle.putString(WithPicCommentActivity.Comment_image_urls, "");
                bundle.putSerializable(WithPicCommentActivity.Comment_notice_json, map);
                bundle.putInt(WithPicCommentActivity.Comment_type, AnswerListType.TYPE_KNOW);
                Intent intent = new Intent();
                intent.putExtras(bundle);
                intent.setClass(this, WithPicCommentActivity.class);
                startActivity(intent);
                // 隐藏弹出的键盘...
                hideKeyboard();
                break;
            case R.id.bar_edit_text:
                /*if (!GlobalContext.getPerfectData()) {
                    Notification.toast(this, "您还未完善资料，无法回复");
                }*/
                break;
            case R.id.right_imagebutton:
                showCollectDialog();
                break;
            default:
                break;
        }
    }

    @Override
    public void onKnowGoodFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onKnowGoodSuccess() {

    }

    /**
     * 显示举报弹出框
     */
    private void showDialog() {
        CommentLongClickHelper.getInstance().showReportDialog(this, ReportType.TYPE_KNOW, knowledgeId);
    }

    /**
     * 显示收藏取消弹出框
     */
    private void showCollectDialog() {
        final Dialog dialog = new Dialog(this, R.style.custom_Dialog);
        try {
            Window win = dialog.getWindow();
            win.getDecorView().setPadding(0, 0, 0, 0);
            win.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setAttributes(lp);
            win.setWindowAnimations(R.style.buttom_animation);
        } catch (Exception e) {
            e.printStackTrace();
        }
        View view = LayoutInflater.from(this).inflate(R.layout.custom_bottom_dialog, null);
        Button replyBtn = (Button) view.findViewById(R.id.custom_bottom_reply);
        View replyLine = (View) view.findViewById(R.id.custom_bottom_reply_line);
        Button copyBtn = (Button) view.findViewById(R.id.custom_bottom_copy);
        View copyLine = (View) view.findViewById(R.id.custom_bottom_copy_line);
        Button reportBtn = (Button) view.findViewById(R.id.custom_bottom_report);
        View reportLine = (View) view.findViewById(R.id.custom_bottom_report_line);
        Button deleteBtn = (Button) view.findViewById(R.id.custom_bottom_delete);
        Button cancelBtn = (Button) view.findViewById(R.id.custom_bottom_cancel);

        reportBtn.setText(knowledgeData.isCollect() == 1 ? getResources().getString(R.string.cancel_collect) : getResources().getString(R.string.collect));

        replyBtn.setVisibility(View.GONE);
        replyLine.setVisibility(View.GONE);
        copyBtn.setVisibility(View.GONE);
        copyLine.setVisibility(View.GONE);
        reportBtn.setVisibility(View.VISIBLE);
        reportLine.setVisibility(View.VISIBLE);
        deleteBtn.setVisibility(View.GONE);


        dialog.setCanceledOnTouchOutside(true);
        reportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                knowledgeCollectManager.knowledgeCollect(knowledgeId);
            }
        });
        // 取消
        cancelBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();


    }


    /**
     * 显示删除弹出框
     */
    private void showDeleteDialog() {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle(getResources().getString(R.string.delete_know_notice));
        builder.setPositiveButton(this.getResources().getString(R.string.confirm),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        delManager.knowledgeDel(GlobalContext.getAccountId(), knowledgeId);
                    }
                });
        builder.setNegativeButton(this.getResources().getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CommentLongClickHelper.getInstance().removeCommentLongClickListener(this);
        if (null != twoComDataChangeManager) {
            twoComDataChangeManager.removeCommentChangeListener(this);
        }
        if (null != manager)
            manager.removeKnowledgeDetailListener(this);
        if (null != goodManger)
            goodManger.removeKnowGoodListener(this);
        if (null != delManager)
            manager.removeKnowledgeDetailListener(this);
        if (null != knowledgeHelper) {
            knowledgeHelper.removeListener(this);
        }
        if (null != scoreReduceManager) {
            scoreReduceManager.removeScoreReduceListener(this);
        }

        if (null != answerDelManger) {
            answerDelManger.removeknowAnswerDelListener(this);
        }
        // 移除绑定的EditText
        if (null != emotionMainFragment) {
            emotionMainFragment.removeEditText();
        }
        if (null != answerAddManger) {
            answerAddManger.removeknowAnswerAddListener(this);
        }
        if (null != answerListManager) {
            answerListManager.removeknowAnswerListListener(this);
        }
        if (null != knowledgeCollectManager) {
            knowledgeCollectManager.removeknowCollectListener(this);
        }
    }

    @Override
    public void onKnowledgeDelFailure(int errorCode, String errorMsg) {
        Notification.toast(this, errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onKnowledgeDelSuccess() {
        knowledgeHelper.deleteNotify(knowledgeId);
        this.finish();
    }

    @Override
    public void addOneKnowledge(KnowledgeData data) {

    }

    @Override
    public void removeOneKnowledge(int knowledgeId) {

    }

    @Override
    public void goodNotify(int knowledgeId, int isGood, int goodCount) {
        if (this.knowledgeId == knowledgeId) {
            knowledgeData.setIsGood(isGood);
            knowledgeData.setGoodCount(goodCount);
            Utils.praiseChanged(this, isGood, goodCount, praiseTV);
        }
    }

    @Override
    public void replyNotify(int knowledgeId, int answerCounts) {
        if (this.knowledgeId == knowledgeId) {
            knowledgeData.setAnswerCount(answerCounts);
            Utils.showPriseCounts(answerCounts, answerTV);
            showCounts(answerCounts);
        }
    }

    @Override
    public void visitorNotify(int knowledgeId, int visitorCounts) {
        if (this.knowledgeId == knowledgeId) {
            knowledgeData.setVisitorCount(visitorCounts);
//            Utils.showVisitorCounts(visitorCounts, visitorTV);
        }
    }

    @Override
    public void modifyOneData(int knowledgeId, KnowledgeData data) {

    }

    @Override
    public void onScoreReduceFailure(int errorCode, String errorMsg) {
        if (errorCode == ErrorCode.NO_SCORE) {
            ErrorDialogHelper.getInstance().showNoScore(this);
        } else {
            Notification.toast(this, errorMsg == null ? "" : errorMsg);
        }
    }

    @Override
    public void onScoreReduceSuccess() {
        reqData();
    }

    @Override
    public void onKnowAnswerListFailure(int errorCode, String errorMsg) {
        waittingLayout.setVisibility(View.GONE);
    }

    @Override
    public void onKnowAnswerListSuccess(List<QuestAnswerListData> list) {
        waittingLayout.setVisibility(View.GONE);
        pullListView.onRefreshComplete(false, false);
        if (null != list) {
            if (IsPullDown) {
                adapter.clear();
            }
            adapter.addData(list);
            adapter.notifyDataSetChanged();
        }

    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        int totalHeight = 0;
        for (int i = 0, len = adapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = adapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    @Override
    public void onKnowAnswerAddFailure(int errorCode, String errorMsg) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        Notification.toast(this, errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onKnowAnswerAddSuccess(QuestAnswerListData obj) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }

        if (null != obj) {
            //通过pid判断是1级回复还是二级回复 pid不为0 则为二级回复
            if (0 != obj.pid) {
                return;
            }
            bar_edit_text.setText("");
            bar_edit_text.setHint(getResources().getString(R.string.qa_detail_hint));
            if (null != replyMap) {
                replyMap.clear();
            }
//            obj.accountId = GlobalContext.getAccountId();
//            obj.goodCount = 0;
            adapter.addOneData(obj);
            adapter.notifyDataSetChanged();
            // 添加一条回答数
            int answerCount = knowledgeData.getAnswerCount();
            answerCount++;
//            knowledgeData.setAnswerCount(answerCount);
//            Utils.showPriseCounts(answerCount, answerTV);
            // 通知外面回复数改变。。。。
            knowledgeHelper.replyNotify(knowledgeId, answerCount);

            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    // 定位到最上面一条数据，位置发生偏移，需要加上两个addHeadview的内容
                    myListView.setSelection(2);
                }
            });
        }

    }

    @Override
    public void commentLongClick(QuestAnswerListData data) {
        answerDelManger.knowAnswerDel(GlobalContext.getAccountId(), data.id);
        adapter.deleteById(data.id);
        // 删除后，回复数减一
        int counts = knowledgeData.getAnswerCount();
        counts--;
//        knowledgeData.setAnswerCount(counts);
//        Utils.showPriseCounts(counts, answerTV);
        knowledgeHelper.replyNotify(data.knowledgeId, counts);
        // 实现代码暂无
    }

    @Override
    public void onKnowAnswerDelFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onKnowAnswerDelSuccess() {

    }

    @Override
    public void onKnowCollectFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onKnowCollectSuccess() {
        if (1 == knowledgeData.isCollect()) {
            knowledgeData.setCollect(0);
            Notification.toast(this, "取消收藏成功");
        } else {
            knowledgeData.setCollect(1);
            Notification.toast(this, "收藏成功");
        }
    }

    class FindClass {
        public int index;
        public String content;
    }

    private List<KnowPraseData> splitImageContentByImages(String content, String noticeJson) {
        List<KnowPraseData> mContentList = new ArrayList<>();
        Pattern p = Pattern.compile("\\{\"image\":[^}]*\\}");
        Matcher m = p.matcher(content);
        List<FindClass> resultList = new ArrayList<>();
        while (m.find()) {
            String tmp = m.group();
            FindClass find = new FindClass();
            find.index = content.indexOf(tmp);
            find.content = tmp;
            resultList.add(find);
        }

        int preIndex = 0;
        for (int i = 0; i < resultList.size(); i++) {
            FindClass find = resultList.get(i);
            String str = "";
            if (find.index > 0) {
                str = content.substring(preIndex, find.index);
                KnowPraseData praseData = new KnowPraseData();
                praseData.index = 0;
                praseData.type = 1;
                praseData.content = str;
                praseData.noticeJson = noticeJson;
                mContentList.add(praseData);
            }
            KnowPraseData data = new KnowPraseData();
            data.index = find.index;
            data.content = find.content;
            data.type = 2;
            data.noticeJson = null;
            mContentList.add(data);
            preIndex = find.index + find.content.length();
        }
        if (preIndex < content.length()) {
            KnowPraseData data = new KnowPraseData();
            data.type = 1;
            data.index = preIndex;
            data.content = content.substring(preIndex, content.length());
            data.noticeJson = noticeJson;
            mContentList.add(data);
        }
        return mContentList;
    }

    public void insertContent(final List<KnowPraseData> urls, final int index) {
        if (index >= urls.size()) {
            return;
        }
        final String url = urls.get(index).content;

        if (url.indexOf(PictureAndTextEditorView.mBitmapStart) != -1) {//判断是否是图片地址
            KnowImageData imageData = praseUrl(url);
            Glide.with(this)
                    .load(GlobalContext.cdndownUrl + imageData.image)
                    .asBitmap()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                            ImageView iv = new ImageView(KnowDetailActivity.this);
                            int window_height = KnowDetailActivity.this.getWindow().getDecorView().getWidth();
                            float ver_padding = KnowDetailActivity.this.getResources().getDimension(R.dimen.dp10);
                            //  图片显示的宽度为控件的宽度减去左右间隙宽度，不减左右间隙会显示两张一样的图片
                            int d_width = window_height - (int) ver_padding - (int) ver_padding;
//                            int d_width = conentLayout.getWidth() - conentLayout.getPaddingRight() - conentLayout.getPaddingLeft();
                            //  根据宽度，算出图片的等比高度
                            int d_height = d_width * bitmap.getHeight() / bitmap.getWidth();
                            bitmap = Bitmap.createScaledBitmap(bitmap, d_width, d_height, true);
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT);
                            lp.setMargins(0, 0, 0, 0);
                            iv.setLayoutParams(lp);
                            iv.setImageBitmap(bitmap);
//                            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                            conentLayout.addView(iv);
                            iv.setOnClickListener(new PicViewListener(index, urls));
                            insertContent(urls, index + 1);
                        }
                    });

        } else {
            //插入文字
            mSpanTextView = new SpanTextView(this);
            mSpanTextView.setGravity(Gravity.CENTER_VERTICAL);
            mSpanTextView.setTextColor(getResources().getColor(R.color.gray_text));
            mSpanTextView.setTextSize(16);
            mSpanTextView.setLineSpacing(DisplayUtils.dp2px(this, 6), 1);
            Utils.showSpanContent(this, urls.get(index).content, urls.get(index).noticeJson, mSpanTextView);
            conentLayout.addView(mSpanTextView);
            insertContent(urls, index + 1);
        }
    }

    private KnowImageData praseUrl(String url) {
        KnowImageData imageData = JsonUtil.toObject(url, KnowImageData.class);
        if (null == imageData) {
            return new KnowImageData();
        }
        imageData.content = url;
        imageData.type = 2;
        return imageData;
    }

    /**
     * 查看图片
     */
    class PicViewListener implements View.OnClickListener {

        private List<KnowPraseData> urls;
        private int index;

        public PicViewListener(int index, List<KnowPraseData> urls) {
            this.urls = urls;
            this.index = index;
        }

        @Override
        public void onClick(View view) {
            int position = 0;
            ArrayList<String> resultList = new ArrayList<>();
            for (int i = 0; i < urls.size(); i++) {
                if (index == i) {
                    position = resultList.size();
                }
                if (urls.get(i).type == 2) {
                    KnowImageData data = praseUrl(urls.get(i).content);
                    resultList.add(GlobalContext.cdndownUrl + data.image);
                }
            }
            // 查看图片详情
            Utils.imageBrower(KnowDetailActivity.this, position, resultList);
        }

        private List<String> getUrls(int index, List<KnowPraseData> list) {
            List<String> resultList = new ArrayList<>();
            for (KnowPraseData praseData : list) {
                if (praseData.type == 2) {
                    KnowImageData data = praseUrl(praseData.content);
                    resultList.add(data.image);
                }
            }
            return resultList;
        }

    }

    TextView.OnEditorActionListener actionListener = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            // 未完善资料，不能回复评论
            if (!GlobalContext.getPerfectData()) {
                ErrorDialogHelper.getInstance().showPerfectAuth(KnowDetailActivity.this);
                return true;
            }
            if (actionId == EditorInfo.IME_ACTION_SEND /*||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER)*/) {
                String comment = bar_edit_text.getText().toString().trim();
                if (null == comment || "".equals(comment)) {
                    Notification.toast(KnowDetailActivity.this, "请输入你的评论!");
                    return false;
                }
                addAnswerComment(comment);
                // 隐藏键盘
                emotionMainFragment.onBackPress();
                return true;
            }
            return false;
        }

    };

    private void addAnswerComment(String comment) {
        // 回复之前 增加等待框
        dialog = LoadingWaitDialog.createLoadingDialog(this, "");
        dialog.setCancelable(false);
        dialog.show();

        answerAddManger.knowAnswerAdd(GlobalContext.getAccountId(), knowledgeId, bar_edit_text.getText().toString(),
                JsonUtil.mapToStringJson(replyMap), null, 0, 0);
    }


    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {
                // 清空输入内容时，清除@效果的hashMap
                bar_edit_text.setHint(getResources().getString(R.string.qa_detail_hint));
                if (null != replyMap) {
                    replyMap.clear();
                }
            }
        }
    };

    float previousX = 0;
    float previousY = 0;
    float softHeight = 0;
    boolean inOutside = true;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                previousX = ev.getRawX();
                previousY = ev.getRawY();
                int[] l = {0, 0};
                bar_image_add_btn.getLocationInWindow(l);
                softHeight = l[1];
                inOutside = ev.getY() < softHeight;
                break;
            case MotionEvent.ACTION_MOVE:
                float dy = previousY - ev.getRawY();
                float dx = previousX - ev.getRawX();
                if ((Math.abs(dy) > 30 || Math.abs(dx) > 30) && inOutside) {
                    hideKeyboard();
                }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onBackPressed() {
        /**
         * 判断是否拦截返回键操作
         */
        if (!emotionMainFragment.isInterceptBackPress()) {
            // 注释这段代码 这个会双击才能退出
            //super.onBackPressed();
            finish();
        }
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        emotionMainFragment.onBackPress();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CODE) {
            if (resultCode == RESULT_OK) {
                String userName = data.getStringExtra(Const.INTENT_NICENAME);
                int friendId = data.getIntExtra(Const.BUNDLE_ACCOUNTID, 0);
                if (userName != null && 0 != friendId) {
                    replyMap.put(friendId, userName);// 加入noticeJson
                    // 光标出插入@
                    int index = bar_edit_text.getSelectionStart();
                    Editable editable = bar_edit_text.getText();
                    editable.insert(index, "@" + userName);
                }
            }
        }
    }

    @Override
    public void addOneTwoCommentData(int id, Childrens childrens) {
        adapter.addOneTwoComment(id, childrens);
    }

    @Override
    public void delOneTwoCommentData(int id, int childId) {
        adapter.removeOneTwoComment(id, childId);
        myListView.setAdapter(adapter);
    }

    @Override
    public void priseCommentNotify(int id, int isGood, int goodCounts) {
        adapter.priseNotify(id, isGood, goodCounts);
    }

    @Override
    public void replyCommentNotify(int id, int answerCounts) {

    }

}